"use strict";

const Controller = require("egg").Controller;

class AuthController extends Controller {
  //注册
  async register() {
    const { ctx, app } = this;
    const { accountNumber, passWord, userName, nickName } = ctx.request.body;
    try {
      let  user = await ctx.service.login.register({ accountNumber, passWord, userName, nickName })
      ctx.body = {
        code:200,
        data:user,
      }
    } catch (error) {
      ctx.body = {
        code: -2,
        data: null,
        message:error.message
      }
    }
  }
  // 登录
  async login() {
    const { ctx, app } = this;
    const { accountNumber, passWord } = ctx.request.body;
    try {
      const account = await this.ctx.service.account.findAccount(accountNumber);
      if (!account) {
        throw new Error("账号不存在，请注册")
      }
      if (account.passWord!=passWord) {
        throw new Error("密码错误")
      }
      const user = await this.ctx.service.user.findUserByAccount(account.id);
      // 生成token
      const token = ctx.helper.getToken({  id: user.id, userName: user.userName,passWord,accountNumber:accountNumber });
      ctx.body = {
        code: 200,
        data: {
          token: token
        }
      }
    } catch (error) {
      ctx.body = {
        code: -1,
        data: null,
        message: error.message
      }
    }

  }
  // 验证token，请求时在header配置 Authorization=`Bearer ${token}`
  // 特别注意：token不能直接发送，要在前面加上Bearer字符串和一个空格
  async index() {
    const { ctx } = this;
    console.log(ctx.state.user);
    ctx.body = { code: 201, msg: "验证成功" };
  }
}

module.exports = AuthController;
